//
//  QCLoginViewController.m
//  QCAppProject
//
//  Created by yjl on 2021/8/19.
//

const CGFloat height = 372.0f;

#import "QCLoginViewController.h"
#import "FDDTimer.h"
#import "QCGradientLayerUtil.h"
#import "QCNetworkManager.h"
#import "QCUserProtocolViewController.h"

static int const secondsCountDown = 60;

@interface QCLoginViewController () <FDDTimerDelegate>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UILabel *titleLbl;
@property (nonatomic, strong) UIView *accountView;
@property (nonatomic, strong) UITextField *accountTF;
@property (nonatomic, strong) UIView *verifyCodeView;
@property (nonatomic, strong) UITextField *verifyCodeTF;

//验证码按钮
@property (nonatomic, strong) UIButton *codeButton;
//登录按钮
@property (nonatomic, strong) UIButton *submitButton;
//计时器
@property (nonatomic, strong) FDDTimer *smsCodeTimer;
//协议
@property (nonatomic, strong) UIButton *serviceButton;

@end

@implementation QCLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)initUI {
    self.view.backgroundColor = QCBgColor;
    [self.view addSubview:self.bgView];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:self.bgView.frame];
    imageview.image = fImageNamed(@"home_bg");
    [self.bgView addSubview:imageview];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.frame = CGRectMake(0, kStatusBarHeight, 60, 40);
    [btn setImage:fImageNamed(@"ic_back_24pt_white") forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(backBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bgView addSubview:btn];
    [self.view addSubview:self.containerView];
    [self.containerView addSubview:self.titleLbl];
    [self.containerView addSubview:self.accountView];
    [self.containerView addSubview:self.verifyCodeView];
    
    [self.accountView addSubview:self.accountTF];
    [self.accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@26);
        make.right.equalTo(@-26);
        make.centerY.equalTo(self.accountView.mas_centerY);
        make.height.equalTo(self.accountView.mas_height);
    }];
    
    [self.verifyCodeView addSubview:self.verifyCodeTF];
    [self.verifyCodeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@26);
        make.width.equalTo(@(self.verifyCodeView.width - 98 - 30));
        make.centerY.equalTo(self.verifyCodeView.mas_centerY);
        make.height.equalTo(self.verifyCodeView.mas_height);
    }];
    
    [self.verifyCodeView addSubview:self.codeButton];
    [self.codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-10);
        make.centerY.equalTo(self.verifyCodeView.mas_centerY);
        make.size.equalTo(@(CGSizeMake(88, 30)));
    }];
    
    [self.containerView addSubview:self.submitButton];
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.top.equalTo(self.verifyCodeView.mas_bottom).offset(33);
        make.width.equalTo(self.verifyCodeView.mas_width);
        make.height.equalTo(@40);
    }];
    
    [self.containerView addSubview:self.serviceButton];
    [self.serviceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.submitButton.mas_bottom).offset(33);
        make.centerX.equalTo(self.containerView.mas_centerX);
        make.width.equalTo(self.containerView.mas_width);
    }];
}

- (void)backBtnAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)codeTextBtnPressed:(id)sender {
    NSString *phone = [self.accountTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (phone.length != 11) {
        [QCProgressHUD showHUDWithMessage:@"请输入正确的手机号～" autoHide:YES];
        return;
    }
    [QCNetworkManager getRequestWithURL:[QCSingleton instance].URL.smsCodeUrl parameters:@{@"userphone" : phone} Progress:nil success:^(id responseObject) {
        self.smsCodeTimer.type = TEXT;
        self.smsCodeTimer.delegate = self;
        self.smsCodeTimer.secondsCountDown = secondsCountDown;
        [self.smsCodeTimer startFDDTimer];
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)loginBtnToClicked {
    NSString *phone = [self.accountTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (phone.length != 11) {
        [QCProgressHUD showHUDWithMessage:@"请输入正确的手机号～" autoHide:YES];
        return;
    }
    NSString *ucode = [self.verifyCodeTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (ucode.length < 4) {
        [QCProgressHUD showHUDWithMessage:@"请输入正确的验证码～" autoHide:YES];
        return;
    }
    [QCProgressHUD showHUDWithWaitingMessage:@""];
    
//    WS(weakSelf)
//    [QCProgressHUD hideHUD];
//    [QCProgressHUD showHUDWithMessage:@"登录成功" autoHide:YES];
//    QCUserInfo *userInfo = [QCUserInfo new];
//    userInfo.account = phone;
//    [QCSingleton instance].userInfo = userInfo;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if (weakSelf.loginSuccessBlock) {
//            weakSelf.loginSuccessBlock();
//        }
//        [self dismissViewControllerAnimated:YES completion:nil];
//    });
    WS(weakSelf)
    [QCNetworkManager getRequestWithURL:[QCSingleton instance].URL.loginUrl parameters:@{@"userphone" : phone,@"ucode" : ucode} Progress:nil success:^(id responseObject) {
        [QCProgressHUD hideHUD];
        [QCProgressHUD showHUDWithMessage:@"登录成功" autoHide:YES];
        QCUserInfo *userInfo = [QCUserInfo new];
        userInfo.account = phone;
        [QCSingleton instance].userInfo = userInfo;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"login_success_refresh" object:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (weakSelf.loginSuccessBlock) {
                weakSelf.loginSuccessBlock();
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        
    } failure:^(NSError *error) {
        [QCProgressHUD hideHUD];
    }];
}

- (void)serviceButtonToClicked {
    [self.navigationController pushViewController:[QCUserProtocolViewController new] animated:YES];
}

#pragma mark - FDDTimerdelegate

- (void)willFDDTimerStart:(FDDTimer *)timer{
    
}

- (void)didFDDTimerStart:(FDDTimer *)timer seconds:(NSInteger)seconds {
    self.codeButton.enabled = NO;
    NSString *str = [NSString stringWithFormat:@"获取中(%lds)",(long)seconds];
    [self.codeButton setTitle:str forState:UIControlStateNormal];
}

- (void)didFDDTimerStop:(FDDTimer *)timer {
    //timer 停止时设置两者都可以点击
    [self.codeButton setTitle:@"重新获取" forState:UIControlStateNormal];
    self.codeButton.enabled = YES;
}

- (void)dealloc {
    [_smsCodeTimer stopFDDTimer];
}

#pragma mark - Textfield观察

- (void)textFieldEditBegin:(UITextField *)field{
}

- (void)textFieldEditEnd:(UITextField *)field{
}


- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180*SCREEN_HEIGHT_SCALE)];
    }
    return _bgView;
}

- (UIView *)containerView {
    if (!_containerView) {
        QCLog(@"%f" ,SCREEN_HEIGHT_SCALE*height);
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(20, (SCREEN_HEIGHT - SCREEN_HEIGHT_SCALE*height)/2, SCREEN_WIDTH - 40, SCREEN_HEIGHT_SCALE*height)];
        _containerView.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
        _containerView.layer.shadowColor = [UIColor colorWithRed:255/255.0 green:161/255.0 blue:77/255.0 alpha:0.19].CGColor;
        _containerView.layer.shadowOffset = CGSizeMake(0,5);
        _containerView.layer.shadowOpacity = 1;
        _containerView.layer.shadowRadius = 15;
        _containerView.layer.cornerRadius = 10;
    }
    return _containerView;
}

- (UILabel *)titleLbl {
    if (!_titleLbl) {
        _titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH - 40, 22)];
        _titleLbl.font = FONT_PR(23);
        _titleLbl.textAlignment = NSTextAlignmentCenter;
        _titleLbl.textColor = QCBlack;
        _titleLbl.text = @"用户登录";
    }
    return _titleLbl;
}

- (UIView *)accountView {
    if (!_accountView) {
        _accountView = [[UIView alloc] initWithFrame:CGRectMake(20, 80, SCREEN_WIDTH - 40 - 40, 46)];
        _accountView.backgroundColor = kHexColor(@"#F5F5F5");
        _accountView.layer.cornerRadius = 23.0f;
        _accountView.layer.masksToBounds = YES;
    }
    return _accountView;
}

- (UITextField *)accountTF{
    if (!_accountTF) {
        _accountTF = [[UITextField alloc] init];
        _accountTF.font = FONT(15);
        _accountTF.placeholder = @"输入手机号码";
        _accountTF.textColor = QCBlack;
        _accountTF.keyboardType = UIKeyboardTypeNumberPad;
        _accountTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _accountTF.textAlignment = NSTextAlignmentLeft;
//        [_accountTF addTarget:self action:@selector(textFieldEditBegin:) forControlEvents:UIControlEventEditingDidBegin];
//        [_accountTF addTarget:self action:@selector(textFieldEditEnd:) forControlEvents:UIControlEventEditingDidEnd];
    }
    return _accountTF;
}

- (UIView *)verifyCodeView {
    if (!_verifyCodeView) {
        _verifyCodeView = [[UIView alloc] initWithFrame:CGRectMake(20,self.accountView.bottom+20, SCREEN_WIDTH - 40 - 40, 46)];
        _verifyCodeView.backgroundColor = kHexColor(@"#F5F5F5");
        _verifyCodeView.layer.cornerRadius = 23.0f;
        _verifyCodeView.layer.masksToBounds = YES;
    }
    return _verifyCodeView;
}

- (UITextField *)verifyCodeTF{
    if (!_verifyCodeTF) {
        _verifyCodeTF = [[UITextField alloc] init];
        _verifyCodeTF.font = FONT(15);
        _verifyCodeTF.placeholder = @"输入验证码";
        _verifyCodeTF.textColor = QCBlack;
        _verifyCodeTF.keyboardType = UIKeyboardTypeNumberPad;
        _verifyCodeTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _verifyCodeTF.textAlignment = NSTextAlignmentLeft;
//        [_verifyCodeTF addTarget:self action:@selector(textFieldEditBegin:) forControlEvents:UIControlEventEditingDidBegin];
//        [_verifyCodeTF addTarget:self action:@selector(textFieldEditEnd:) forControlEvents:UIControlEventEditingDidEnd];
    }
    return _verifyCodeTF;
}

-(UIButton *)codeButton {
    if (!_codeButton) {
        _codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _codeButton.titleLabel.font = FONT_PR(13);
        _codeButton.backgroundColor = QCOrange;
        [_codeButton setTitleColor:QCWhite forState:UIControlStateNormal];
        _codeButton.layer.cornerRadius = 15.0f;
        _codeButton.layer.masksToBounds = YES;
        [QCGradientLayerUtil configLayerGradientColor:_codeButton originColor:kHexColor(@"#FF5100") targetColor:kHexColor(@"#FFB15C")];
        //获取验证码
        [_codeButton addTarget:self action:@selector(codeTextBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeButton;
}


- (FDDTimer *)smsCodeTimer {
    if (!_smsCodeTimer) {
        _smsCodeTimer = [[FDDTimer alloc] initWithSecoundCount:secondsCountDown type:TEXT];
        _smsCodeTimer.delegate = self;
    }
    return _smsCodeTimer;
}

- (UIButton *)submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _submitButton.titleLabel.font = FONT_PR(20);
        [_submitButton setTitle:@"确定登录" forState:(UIControlStateNormal)];
        [_submitButton setTitleColor:QCWhite forState:(UIControlStateNormal)];
        _submitButton.backgroundColor = QCOrange;
        _submitButton.layer.cornerRadius = 20.0f;
        [_submitButton addTarget:self action:@selector(loginBtnToClicked) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _submitButton;
}

- (UIButton *)serviceButton {
    if (!_serviceButton) {
        _serviceButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _serviceButton.titleLabel.font = FONT_PR(13);
        [_serviceButton setTitle:@"注册即可表明同意《用户协议》" forState:(UIControlStateNormal)];
        [_serviceButton setTitleColor:QCOrange forState:(UIControlStateNormal)];
        [_serviceButton addTarget:self action:@selector(serviceButtonToClicked) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _serviceButton;
}

@end
